package com.sitech.portal.server.action;

import com.sitech.ibnms.core.IPage;
import com.sitech.ibnms.core.JGridBaseAction;
import com.sitech.ibnms.util.RandomGUID;
import com.sitech.portal.server.service.INewsService;
import com.sitech.portal.system.domain.TblSYS_LOGINMSG;
import org.apache.struts2.ServletActionContext;

import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

public class NewsAction extends JGridBaseAction {

    private INewsService newsService;
    private HashMap<String,String> news=new HashMap();
    private List ids;
    private List<HashMap> newsList;
    private String savePath;
    private File file;
    private String fileFileName;
    private HashMap<String,String> map = new HashMap();
    private String saveFilePath = "newsFile";
    private InputStream inputStream;
    private String id;
    private boolean flag;



    public void setNewsService(INewsService newsService) {
        this.newsService = newsService;
    }

    public String loadAddNews() {
        String id = this.getRequest().getParameter("id");
        if(id!=null){
          news =  newsService.selectNews(id);
            if(news.get("FILE_PATH")!=null){
                news.put("FILE_PATH", news.get("FILE_PATH").replaceAll("\\\\", "//")) ;
            }

        };
        return SUCCESS;
    }
    public String addNews() {
        flag = true;
        TblSYS_LOGINMSG user = this.getCurrentUser();
        news.put("LOGIN_ID",user.getLOGIN_ID());
        if(news.get("ID")!=null && !news.get("ID").equals("")){
           flag =  newsService.canBeModify(news.get("ID"));
            if(!flag){
                return SUCCESS;
            }
        }
        newsService.insertNews(news);
        return SUCCESS;
    }
    public String newsList() {

        IPage result = newsService.selectNewsList(news, this.getPageForm());
        setResult(result);
        return SUCCESS;
    }

    public String delNews() {
        TblSYS_LOGINMSG user = this.getCurrentUser();
        newsService.deleteNews(ids,user.getLOGIN_ID());
        return SUCCESS;
    }


    public String loadUnreadNews() {
        TblSYS_LOGINMSG user = this.getCurrentUser();
        newsList = newsService.selectUnReadNews(user.getLOGIN_ID());
        return SUCCESS;
    }

    public String readNews() {
        TblSYS_LOGINMSG user = this.getCurrentUser();
        newsService.updateReadNews(user.getLOGIN_ID(), ids);
        return SUCCESS;
    }

    public String uploadNews(){
        savePath = this.getRequest().getSession().getServletContext().getRealPath("/");
        savePath = savePath+saveFilePath;
        FileInputStream fis = null;
        String serverPath = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(file);
            Integer size = fis.available();
            //创建文件目录
            //保存路径
            //目录不存在则创建
            File fileDir = new File(savePath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            String tmpFileName = UUID.randomUUID().toString();
            String fileSuffix = fileFileName.substring(fileFileName.lastIndexOf("."));
            //文件保存路径
            serverPath = savePath + File.separator + tmpFileName + fileSuffix;
            fos = new FileOutputStream(serverPath);
            byte buffer[] = new byte[size];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            this.getResponse().setCharacterEncoding("UTF-8");
            this.getResponse().setContentType("text/plain");
            this.getResponse().getWriter().append(serverPath);
        } catch (IOException e){
        } finally {
            try {
                if(null != fos){
                    fos.flush();
                    fos.close();
                }
                if(null != fis){
                    fis.close();
                }
            } catch (IOException e) {
            }
        }
        return null;
    }

    public String saveNewsFileDb(){
        TblSYS_LOGINMSG user = this.getCurrentUser();
        map.put("CREATE_USER", user.getLOGIN_ID());
        map = newsService.saveNewsFileDb(map);
        return SUCCESS;
    }

    public String delFile(){
        file = new File(savePath);
        System.out.println("删除："+savePath);
        if (!file.exists()) {
            return SUCCESS;
        } else {
            if (file.isFile()&& file.exists()) {
                 file.delete();
            }
        }
        return SUCCESS;
    }

    public String download(){
        try {
            fileFileName = java.net.URLEncoder.encode(fileFileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return SUCCESS;
    }

    public InputStream getInputStream() {
        try {
            String webroot= this.getRequest().getSession().getServletContext().getRealPath("/");
            String path = webroot+URLDecoder.decode(savePath, "UTF-8").replaceAll("///",File.separator );
            System.out.println("下载："+path);
            return new FileInputStream(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return null;
    }

    public String hisNewsList() {
        TblSYS_LOGINMSG user = this.getCurrentUser();
        news.put("CURRENT_USER", user.getLOGIN_ID());
        IPage result = newsService.selectHisNewsList(news, this.getPageForm());
        setResult(result);
        return SUCCESS;
    }


    public String recordPopNews() {
        TblSYS_LOGINMSG user = this.getCurrentUser();
        newsService.updatePopNews(user.getLOGIN_ID(), id);
        return SUCCESS;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public HashMap<String, String> getNews() {
        return news;
    }

    public void setNews(HashMap<String, String> news) {
        this.news = news;
    }

    public List getIds() {
        return ids;
    }

    public void setIds(List ids) {
        this.ids = ids;
    }

    public List<HashMap> getNewsList() {
        return newsList;
    }

    public void setNewsList(List<HashMap> newsList) {
        this.newsList = newsList;
    }

    public String getSavePath() {
        return savePath;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public HashMap<String, String> getMap() {
        return map;
    }

    public void setMap(HashMap<String, String> map) {
        this.map = map;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}

